define(function(require, exports) {
	var $ = require("jquery");
	var util = require('util');
	var pubjs = require('pubjs');
	var view = require('@base/view');
	var upload = require('modules/upload');
	var dropdown = require('@base/common/drop').drop;
	var dialog = require('@base/dialog');
	var Input = require('@base/common/input');

	// 补充资质证件信息
	var EXTRA_INFO = pubjs.config('certificateExtra');
	var EXTRA_FIELD = [];
	var EXTRA_MAP = {};
	util.each(EXTRA_INFO, function(item)
	{
		EXTRA_FIELD.push(item.field);
		EXTRA_MAP[item.field] = item;
	});


	// 转换资质数据，方便后续使用
	var certificateList = pubjs.config('certificateList');
	var certificateMap = {};
	if (certificateList && certificateList.length)
	{
		util.each(certificateList, function(item)
		{
			certificateMap[item._id] = item;
		});
	}


	// 新建资质-资质证件列表
	var Base = view.container.extend({
		init: function(config) {
			config = pubjs.conf(config, {
				'limit': 20,
				'certificateType': {
					// 'def': LANG('选择资质证件名称'),
					'width': 250,
					// 'option_height': 180,
					'key': '_id',
					'name': 'Name',
					// 'isPopUp': false,
					'value': 0,
					'options': pubjs.config('certificateList'),
					'panel_config': {
						'height': 200
					}
				},
				'class': 'P-adminAptitudeCertificate'
			});

			this.$showUrlName = [];
			this.$itemPrefix = 'CERTIFICATE_ITEM_';
			this.$TypePrefix = 'TYPE_';
			this.Super('init', arguments);
		},
		afterBuild: function() {
			this.append([
				'<table class="table table-bordered">',
					'<thead>',
						'<tr>',
							'<th class="w50pct tc">' + LANG('证件类型') + '<span pub-name="textTip" pub-mod="@base/tip.desc" class="textTip"/></th>',
							'<th class="w40pct tc">' + LANG('素材') + '</th>',
							'<th class="w10pct tc">' + LANG('操作') + '</th>',
						'</tr>',
					'</thead>',
					'<tbody />',
				'</table>',
				'<div class="mt15 mb20">',
					'<button class="btn btn-default btnAddItem mr10">' + LANG("上传其它证件") + '</button>',
					'<span class="ml15">' + LANG("请上传图片格式文件，文件尺寸小于1MB。") + '</span>',
				'</div>'
			].join(''));

			this.$listContainer = this.find('tbody');
			this.uiBind(this.find('.btnAddItem'), 'click', 'eventAddBtnClick');
			this.buildFromTemplate({
				'textTip': {
					'width': 300,
					'data': LANG("请选择证件名")
				}
			});
			this.reset();
		},
		reset: function() {
			this.$listContainer.empty();
			this.$rows = [];
			this.addRow();
			return this;
		},
		getData: function() {
			var self = this;
			var data = [];

			util.each(self.$rows, function(row) {
				var dropdown = self.$[self.$TypePrefix + row.id];

				var dropdownData = dropdown.getValue(true);
				var item = {
					'Name': dropdownData.name,
					'TypeId':dropdownData.id,


					//图片文件的默认字段
					'FileId'		: '',
					'Thumb'			: '',
					'Width'			: 0,
					'Height'		: 0,

					//生成tanx的默认字段信息
					'IsTanx'		: true,
					'TanxUrl'		: '',
					'TanxId'		: '',
					'TanxStatus'	: '',
					'TanxReason'	: ''
				};

				var typeData = certificateMap[item.TypeId];

				if (!typeData) {
					// pubjs.error("未知的证件类型");
					return;
				}

				var uploaderData;
				if (typeData.Type == 'ZIP')
				{
					uploaderData = self.$[row.id + 'zip'].getValue().shift() || {};
				}
				else
				{
					uploaderData = self.$[row.id].getValue().shift() || {};
				}

				switch(typeData.Type) {
					// 素材是图片类型
					case 'IMAGE':
						util.extend(item, {
							FileId: uploaderData.fileId,
							Thumb: uploaderData.thumb,
							Width: uploaderData.width,
							Height: uploaderData.height
						});
					break;
					// 素材是url类型
					case 'TEXT':
						item.TanxUrl = row.urlInput.val() || "";
					break;
					case 'ZIP':
						util.extend(item, {
							FileId: uploaderData.fileId
						});
					break;
				}


				//为了兼容旧数据没有fileId,将path和image一同获取和发送
				if (row.data) {
					item.Path = row.data.Path || '';
					item.Image = row.data.Image || '';
				}

				// 补充资质信息
				var extraData = row.extra.getData();
				util.each(extraData, function(value, key)
				{
					item[key] = value || '';
				});

				data.push(item);
			});
			return data;
		},
		setData: function(data) {
			var self = this;
			var rows = self.$rows;
			var c = self.getConfig();

			while(data && rows.length < data.length && rows.length < (c.limit || 20)) {
				self.addRow();
			}

			util.each(rows, function(row, index) {
				var item = data[index];
				var dropdown = self.$[self.$TypePrefix + row.id];
				if (item) {
					dropdown.setValue(item.TypeId);

					var typeData = certificateMap[item.TypeId];

					if (!typeData) {
						pubjs.error("未知的证件类型");
						return;
					}

					switch(typeData.Type) {
						// 素材是图片类型
						case 'IMAGE':
							var thumb = item.Thumb;
							var path = item.Image || item.Path;
							//兼容旧数据，如果文件url以http开头的，直接使用该url
							if (path && !path.indexOf('http'))
							{
								thumb =	path;
							}
							self.$[row.id].setValue({
								// id: row.id,
								// fileId: item.FileId,
								id: item.FileId,
								thumb: thumb,
								width: item.Width,
								height: item.Height
							});
						break;
						// 素材是url类型
						case 'TEXT':
							row.urlInput.val(item.TanxUrl || "");
						break;
						// 素材是zip类型
						case 'ZIP':
							self.$[row.id + 'zip'].setValue({
								id: item.FileId,
								thumb: thumb
							});
						break;
					}

					row.data = item;

					//上传图片和文本输入框显隐
					row.imageCon.toggle(typeData.Type == 'IMAGE');
					row.urlCon.toggle(typeData.Type == 'TEXT');
					row.zipCon.toggle(typeData.Type == 'ZIP');

					//资质证件审核资质状态。
					if (item.hasOwnProperty('TanxStatus'))
					{
						var map = {
							'0': LANG('待审核'),
							'1': LANG('审核通过'),
							'-1': LANG('审核未通过-原因:'),
							'-2': LANG('审核中')
						};
						var reason = map[item.TanxStatus];
						if (item.TanxStatus == -1)
						{
							reason += item.TanxReason;
						}
						row.reason.append(reason);
					}

					// 补充资质信息
					row.extra.setData(item);
				}
			});

			self.$data = data;
		},
		validate: function(data) {
			data = data || this.getData();
			var ret = true;
			util.each(data, function(item) {
				// 是否上传了素材
				// var hasContent = item.FileId || item.TanxUrl;
				var hasContent = item.FileId || item.Image || item.Path || item.TanxUrl;

				if (item.TypeId && !hasContent) {
					pubjs.alert(LANG("素材不能为空"));
					ret = false;
					return false;
				}

				if (!item.TypeId && hasContent) {
					pubjs.alert(LANG('请选择相应的证件资质名称'));
					ret = false;
					return false;
				}
			});

			return ret;
		},
		validateExtra: function(data)
		{
			var state = true;
			// 检查补充证件信息, 查看是否有勾选需要必填补充信息的渠道
			var checkExtra = false;
			var needCrtExtra = pubjs.config('exchange_group_needCrtExtra');
			util.each(data.Info, function(item)
			{
				if (needCrtExtra.indexOf(+item.ExchangeId) != -1)
				{
					checkExtra = true;
					return false;
				}
			});


			// 需要检查补充字段
			if (checkExtra)
			{
				// 需要校验补充信息是否填写的证件id集合
				var validateCrtExtraIds = pubjs.config('validateCrtExtra');
				// 检查每个证件
				util.each(data.Materials, function(item)
				{
					if (validateCrtExtraIds.indexOf(+item.TypeId) != -1)
					{
						var emptyField = '';
						// 检查每个补充字段是否都有填写
						util.each(EXTRA_FIELD, function(field)
						{
							if (!item[field])
							{
								emptyField = field;
								return false;
							}
						});

						// 如果有字段为空，则弹窗提示
						if (emptyField)
						{
							var CrtName = certificateMap[item.TypeId] && certificateMap[item.TypeId].Name;
							var tip = LANG('需要“') + CrtName + LANG('”的详细资质信息，请补充');
							// tip += LANG('请填写') + (EXTRA_MAP[emptyField] && EXTRA_MAP[emptyField].title);
							pubjs.alert(tip)
							state = false;
							return false;
						}
					}
				});
			}

			return state;
		},
		removeRow: function(id) {
			var rows = this.$rows;
			var index = util.index(rows, id, 'id');

			if (index !== null) {
				this.$[id].destroy();
				rows[index].el.remove();
				rows.splice(index, 1);
			}
		},
		// 证件类型切换消息，联动素材
		onDropChange: function (ev) {
			var typeMod = ev.name;
			var option = ev.param && ev.param.option;
			if (typeMod && typeMod.indexOf(this.$TypePrefix) === 0) {
				var row = util.find(this.$rows, typeMod, 'typeMod');
				// 如果是url类型则显示url
				if (row)
				{
					row.imageCon.toggle(option.Type == 'IMAGE');
					row.urlCon.toggle(option.Type == 'TEXT');
					row.zipCon.toggle(option.Type == 'ZIP');
				}
			}
			return false;
		},
		addRow: function() {
			var rows = this.$rows;
			var c = this.getConfig();

			if (rows.length >= c.limit) {
				return pubjs.alert(LANG("最多只允许添加%1个证件", c.limit));
			}

			var con = this.$listContainer;
			var id = this.$itemPrefix + util.guid();
			var tr = $('<tr data-id="' + id + '" />').appendTo(con);
			//var input = $('<td><input type="text" placeholder="' + LANG("请输入证件名") + '" /></td>').appendTo(tr).find('input');
			var dropdownTd = $('<td></td>').appendTo(tr);
			var contentTd = $('<td class="tc"/>').appendTo(tr);
			var imageCon = $('<span/>').appendTo(contentTd);
			var urlCon = $('<span/>').appendTo(contentTd).hide();
			var zipCon = $('<span/>').appendTo(contentTd).hide();
			var op = $('<td class="tc"/>').appendTo(tr);
			var removeBtn = $('<i class="uk-icon-times-circle cur_p" />').css('font-size', 22).appendTo(op);

			this.uiBind(removeBtn, 'click', id, 'evRemoveBtnClick');

			this.create(id, upload.base, util.extend({
				'target': imageCon,
				'hasProgress': false
			}, pubjs.config('uploader/certificate')));

			this.create(id + 'zip', upload.base, util.extend({
				'target': zipCon,
				'hasProgress': false
			}, pubjs.config('uploader/certificate_zip')));

			var typeMod = this.$TypePrefix + id;
			this.create(typeMod, dropdown, util.extend({
				'target': dropdownTd
			}, this.getConfig('certificateType')));

			// 补充资质信息
			var extraCon = $('<span class="dib"/>').appendTo(dropdownTd);
			var extraMod = this.create(this.$ExtraPrefix + id, SelectExtra, {
				'target': extraCon
			});

			var reason = $('<span class="ml15"/>').appendTo(dropdownTd);

			rows.push({
				el: tr,
				id: id,
				typeMod: typeMod,
				imageCon: imageCon,
				urlCon: urlCon,
				zipCon: zipCon,
				urlInput: $('<input type="text" class="w200" />').appendTo(urlCon),
				removeBtn: removeBtn,
				reason: reason,
				extra: extraMod
			});
		},
		eventAddBtnClick: function(evt) {
			this.addRow();
		},
		evRemoveBtnClick: function(evt, elm) {
			this.uiUnbind(elm, 'click');
			this.removeRow(evt.data);
		}
	});
	exports.base = Base;


	// 证件补充信息
	var SelectExtra = view.container.extend({
		init: function(config)
		{
			config = pubjs.conf(config, {
				'view_model': {
					'eventClick': this.eventClick
				}
			});

			this.Super('init', arguments);
		},
		afterBuild: function()
		{
			var el = this.getDOM();

			$([
				'<span class="ml15 btn btn-default extraBtn" ms-click="eventClick">'+ LANG('补充资质信息') +'</span>',
				'<span pub-name="popwin" pub-mod="admin/aptitude/modules/certificate.popwinExtra"/>'
			].join('')).appendTo(el);

			this.$extraBtn = el.find('.extraBtn');

			this.buildFromTemplate({

			});
		},
		eventClick: function()
		{
			this.$.popwin.show();
		},
		setData: function(data)
		{
			this.$data = data || {};
			this.$.popwin.setData(this.$data);
			return this;
		},
		getData: function()
		{
			return this.$.popwin.getData();
		},
		reset: function()
		{
			this.$data = {};
			this.hide();
			return this;
		},
		show: function()
		{
			this.$extraBtn.show();
			return this;
		},
		hide: function()
		{
			this.$extraBtn.hide();
			this.$.popwin.hide();
			return this;
		}
	});
	exports.selectExtra = SelectExtra;

	var PopwinExtra = dialog.base.extend({
		init: function(config)
		{
			config = pubjs.conf(config, {
				'title': LANG('补充资质信息'),
				'size': 's',
				"buttonConfig":{
					// 确定按钮样式
					"ok": {
						"type":"button"
						,"layout":null
						,"value":LANG("确定")
						,"class":"btn btn-success"
						,"width": 100
						,"attr":{"data-action":"onOk"}
						,"events":"click"
					}
				}
			});

			this.$param = EXTRA_INFO;
			this.$modNames = [];
			this.Super('init', arguments);
		},
		afterBuild: function()
		{
			this.Super('afterBuild', arguments);

			this.buildItems();
		},
		// 创建新的模块
		buildItems: function()
		{
			var self = this;
			var cs = self.$;
			var el = self.getDOM();
			util.each(self.$param, function(item)
			{
				var con = $('<div class="M-formConGroup"></div>').appendTo(el);
				var title = $('<label class="group-label">'+ LANG(item.title) + '：' +'</label>').appendTo(con);
				var main = $('<div class="group-content"/>').appendTo(con);

				self.create(item.field, Input.text, {
					'target': main,
					'width': 250
				});
			});
			return this;
		},
		getData: function()
		{
			var self = this;
			var cs = self.$;

			// 获取对应字段的值
			var data = {};
			util.each(EXTRA_FIELD, function(name)
			{
				data[name] = util.trim(cs[name].getValue() || '');
			});
			return data;
		},
		setData: function(data)
		{
			var self = this;
			var cs = self.$;

			// 设置对应字段的值
			util.each(EXTRA_FIELD, function(name)
			{
				cs[name].setValue(data[name] || '');
			});
			return this;
		},
		onOk: function()
		{
			this.Super('onOk', arguments);
			this.hide();
			return this;
		}
	});
	exports.popwinExtra = PopwinExtra;
});